package cn.zhouyafeng.itchat4j;

import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.thread.ThreadUtil;
import cn.zhouyafeng.itchat4j.core.Core;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import cn.zhouyafeng.itchat4j.controller.LoginController;
import cn.zhouyafeng.itchat4j.core.MsgCenter;
import cn.zhouyafeng.itchat4j.face.IMsgHandlerFace;

import java.util.ArrayList;
import java.util.Collections;
import java.util.List;

public final class Wechat {
    private static final List<Core> croes = Collections.synchronizedList(new ArrayList<>());
    private static String ROOT_DIR = "";

    static {
        System.setProperty("jsse.enableSNIExtension", "false"); // 防止SSL错误
    }

    private Wechat() {
    }

    public static void newClient(IMsgHandlerFace msgHandler) {
        Client client = new Client(msgHandler, croes.size() == 0);
        ThreadUtil.execute(client);
    }

    public static List<Core> getCroes() {
        return croes;
    }

    public static String getRootDir() {
        return ROOT_DIR;
    }

    public static void setRootDir(String rootDir) {
        ROOT_DIR = rootDir;
    }

    private static class Client implements Runnable {
        private Logger logger = LoggerFactory.getLogger(Client.class);
        private IMsgHandlerFace msgHandler;
        private Core core;

        public Client(IMsgHandlerFace msgHandler, boolean useHotReload) {
            this.msgHandler = msgHandler;
            this.core = Core.newInstance(useHotReload);
            Wechat.croes.add(core);
        }

        @Override
        public void run() {
            try {
                ThreadUtil.newThread(() -> {
                    // 登陆
                    LoginController.login(core);
                    logger.info("第{}个客户端+++++++++++++++++++开始消息处理+++++++++++++++++++++", Wechat.croes.indexOf(core) + 1);
                    msgHandler.setCore(core);
                    core.getThreadPool().execute(() -> MsgCenter.handleMsg(msgHandler));
                }, "微信启动线程" + Wechat.croes.indexOf(core)).start();
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
    }
}